package de.logicline.cvss.ui.view;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.IOpenEventListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.team.internal.ccvs.ui.CVSUIMessages;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.ccvs.ui.actions.ShowResourceInHistoryAction;
import org.eclipse.team.internal.core.history.LocalFileRevision;
import org.eclipse.team.internal.ui.TeamUIPlugin;
import org.eclipse.team.internal.ui.actions.CompareRevisionAction;
import org.eclipse.team.internal.ui.actions.OpenRevisionAction;
import org.eclipse.team.internal.ui.history.GenericHistoryView;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.ViewPart;

import de.logicline.cvss.ui.nls.Messages;
import de.logicline.cvss.ui.popup.action.SearchAction.BackgroundJob;
import de.logicline.cvss.ui.view.list.ListContentProvider;
import de.logicline.cvss.ui.view.list.ListLabelProvider;
import de.logicline.cvss.ui.view.table.TableContentProvider;
import de.logicline.cvss.ui.view.table.TableLabelProvider;
import de.logicline.cvss.util.TableBuilder;
import de.logicline.cvss.vo.CVSSearchEntry;

public class SearchResultView extends ViewPart{

	private Action action1;
	private Action action2;
	private Action doubleClickAction;
//	private Action doubleClickInList;

//	private CompareRevisionAction compareAction;
//	private OpenRevisionAction openAction;
	
	private TableViewer viewer;
	private java.util.List currentCvsSearchEntries;
	
	private ListViewer listViewer;
	
	
	/* (non-Javadoc)
	 * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
	 */
	public void createPartControl(Composite parent) {
		SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
		sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
		
		createTable(sashForm);
		createList(sashForm);
		
		sashForm.setWeights(new int[]{70, 30});
		this.getSite(); // this helps to get the site
		makeActions();
		hookContextMenu();
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
		viewer.addSelectionChangedListener(new ISelectionChangedListener(){
			public void selectionChanged(SelectionChangedEvent event) {
				TableItem[] tableItems = viewer.getTable().getSelection();
				if (tableItems.length == 1) {
					CVSSearchEntry cvsLE = (CVSSearchEntry) tableItems[0].getData();
					
					Object[] oArray = cvsLE.getFiles().toArray();
					String[] sArray = new String[oArray.length];
					
					java.util.List resources = cvsLE.getResources();
					
					cvsLE.getFiles().toArray(sArray);
					
					java.util.List blub = cvsLE.getFilePaths();
					java.util.List files = new ArrayList();
					for (int i=0; i<blub.size(); i++) {
						File file = new File((String) blub.get(i));
						IFile resource ;
						//cvsLE.addFilePaths("");
						files.add(file);
//						listViewer.setData(((IResource)resources.get(i)).getFullPath().toString(), resources.get(i));
						
					}
					
					
					//listViewer.getList().setItems(sArray);
					//listViewer.setInput(cvsLE.getFiles());
//					listViewer.setInput(files);
					listViewer.getList().setData(resources);
					listViewer.setInput(resources);
				}
		}});

//		hookContextMenu();
		contributeToActionBars();
		
	}

	public void setFocus() {
		viewer.getControl().setFocus();
		
	}
	
	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	/**
	 * Adds Actions to the toolbar of the view
	 * @param manager
	 */
	private void fillLocalToolBar(IToolBarManager manager) {
//		manager.add(action1);
//		manager.add(action2);
	}
	
	/**
	 * Adds Actions to the pull down menu of the view
	 * @param manager
	 */
	private void fillLocalPullDown(IMenuManager manager) {
//		manager.add(action1);
//		manager.add(new Separator());
//		manager.add(action2);
	}
	
	/**
	 * Adds Actions to the context menu of the table viewer. 
	 *
	 */
	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				
				if (listViewer.getList().getItemCount() > 0
						&& listViewer.getList().getSelectionIndex() != -1) {
				
					manager.add(action1);
					manager.add(action2);
					// Other plug-ins can contribute there actions here
					manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
				}
			}
		});
		Menu menu = menuMgr.createContextMenu(listViewer.getControl());
		listViewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, listViewer);
	}
	
	private void createTable(Composite parent) {
		TableBuilder builder = new TableBuilder(parent);
		builder.createColumns(4);
		builder.setColumnNames(new String[]{
				Messages.search_view_table_column_header_author, 
				Messages.search_view_table_column_header_date,
				Messages.search_view_table_column_header_comment,
				Messages.search_view_table_column_header_tag
		});
		builder.setColumnWeights(new int[] {20, 20, 40, 20} );
		viewer = builder.getViewer();

		//java.util.List images = getImageList();
		
		viewer.setContentProvider(new TableContentProvider());
		viewer.setLabelProvider(new TableLabelProvider());
		
		//viewer.setInput(images);
		/*
		viewer = new TableViewer(table, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());
		*/
	}

	private java.util.List getImageList() {
		java.util.List images = new ArrayList();
		Field[] fields = ISharedImages.class.getFields();
		for (int i=0; i<fields.length; i++) {
			Field field = fields[i];
			try {
				Object obj = field.get("");				
				//Image image= Activator.getDefault().getWorkbench().getSharedImages().getImage( obj.toString());
				//images.add(image);		
				Image image = CVSUIPlugin.getPlugin().getWorkbench().getSharedImages().getImage( obj.toString());
				images.add(image);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return images;
	}
	

	/**
	 * Creates the List with all the checked in resources.
	 * @param parent
	 */
	private void createList(Composite parent) {
		List list = new List(parent,SWT.Selection | SWT.V_SCROLL);
		
		listViewer = new ListViewer(list);
		
		listViewer.setContentProvider(new ListContentProvider());
		listViewer.setLabelProvider(new ListLabelProvider());
		
		
		
//		listViewer.addDoubleClickListener(new IDoubleClickListener(){
//
//			public void doubleClick(DoubleClickEvent event) {
//				doubleClickInList.run();
//				
//			}});
		
		//Click Compare action
//		openAction = new OpenRevisionAction(CVSUIMessages.CVSHistoryPage_OpenAction);
//		listViewer.getList().addSelectionListener(new SelectionAdapter(){
//			public void widgetSelected(SelectionEvent e) {
//				openAction.selectionChanged((IStructuredSelection) listViewer.getSelection());
//			}
//		});
		//openAction.setPage(this);
		
//		OpenStrategy handler = new OpenStrategy(listViewer.getList());
//		handler.addOpenListener(new IOpenEventListener() {
//			public void handleOpen(SelectionEvent e) {
//					StructuredSelection tableStructuredSelection = (StructuredSelection) listViewer.getSelection();
//					if (false){
////						StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()});
////						compareAction.selectionChanged(sel);
////						compareAction.run();
//					} else {
//						//Pass in the entire structured selection to allow for multiple editor openings
//						StructuredSelection sel = tableStructuredSelection;
//						openAction.selectionChanged(sel);
//						openAction.run();
//					}
//				}
//			});
		

		
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				java.util.List  resources = (java.util.List) listViewer.getList().getData();
				IResource resource = (IResource) resources.get(listViewer.getList().getSelectionIndex());
				GenericHistoryView view = null;
				try {
					view = (GenericHistoryView) TeamUIPlugin.getActivePage().showView(GenericHistoryView.VIEW_ID);
				} catch (PartInitException e) {
					// TODO do something meaningful
					e.printStackTrace();
				}
				if (view != null) {
					view.itemDropped(resource,true);
				}
			}
		};
		action1.setText(Messages.search_result_view_in_History);
		action1.setToolTipText(Messages.search_result_view_in_History_tooltip);
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor("nl$/icons/full/etool16/history.gif"));//ISharedImages.IMG_OBJS_INFO_TSK));
		
		
		action2 = new Action() {
			public void run() {
				showMessage("blub");
				java.util.List  resources = (java.util.List) listViewer.getList().getData();
				IResource resource = (IResource) resources.get(listViewer.getList().getSelectionIndex());
				
				if (resource instanceof IFile) {
				IFile file = (IFile) resource;
				
				
//				try {
//					String id = getEditorID(file.getName(), file.getContents());
//				} catch (CoreException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				try {
					IDE.openEditor(SearchResultView.this.getSite().getPage(), (IFile) file);
				} catch (PartInitException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
				
//				new LocalFileRevision(resource);
			}
			/* private */ String getEditorID(String fileName, InputStream contents) {
				IWorkbench workbench = TeamUIPlugin.getPlugin().getWorkbench();
				IEditorRegistry registry = workbench.getEditorRegistry();
				IContentType type = null;
				if (contents != null) {
					try {
						type = Platform.getContentTypeManager().findContentTypeFor(contents, fileName);
					} catch (IOException e) {

					}
				}
				if (type == null) {
					type = Platform.getContentTypeManager().findContentTypeFor(fileName);
				}
				IEditorDescriptor descriptor = registry.getDefaultEditor(fileName, type);
				String id;
				if (descriptor == null ||
					descriptor.isOpenExternal()) {
					id = "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$
				} else {
					id = descriptor.getId();
				}

				return id;
			}
		};
		action2.setText(Messages.search_result_view_in_Editor);
		action2.setToolTipText(Messages.search_result_view_in_Editor_tooltip);
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));

		
//		doubleClickInList = new Action() {
//			public void run() {
//				ISelection selection = listViewer.getSelection();
//				Object obj = ((IStructuredSelection)selection).getFirstElement();
//				//showMessage("Double-click detected on "+obj.toString());
//				
////				run(new IRunnableWithProgress() {
////					public void run(IProgressMonitor monitor) throws InvocationTargetException {
////						IResource[] resources = getSelectedResources();
////						if (resources.length != 1) return;
////						GenericHistoryView view = (GenericHistoryView)showView(GenericHistoryView.VIEW_ID);
////						if (view != null) {
////							view.itemDropped(resources[0],true);
////						}
////					}
////				}, false /* cancelable */, PROGRESS_BUSYCURSOR);
//				
//				
////				IFile file = null ;//= <choose the file to open>;
////				   IWorkbenchPage page = null;// = <the page to open the editor in>;
////				   HashMap map = new HashMap();
////				   map.put(IMarker.LINE_NUMBER, new Integer(5));
////				   map.put(IWorkbenchPage.EDITOR_ID_ATTR, 
////				      "org.eclipse.ui.DefaultTextEditor");
////				   IMarker marker = null;
////				try {
////					marker = file.createMarker(IMarker.TEXT);
////				} catch (CoreException e) {
////					// TODO Auto-generated catch block
////					e.printStackTrace();
////				}
////				   try {
////					marker.setAttributes(map);
////				} catch (CoreException e) {
////					// TODO Auto-generated catch block
////					e.printStackTrace();
////				}
////				   //page.openEditor(marker); //2.1 API
////				   try {
////					IDE.openEditor(page, marker);
////				} catch (PartInitException e) {
////					// TODO Auto-generated catch block
////					e.printStackTrace();
////				} //3.0 API
////				   try {
////					marker.delete();
////				} catch (CoreException e) {
////					// TODO Auto-generated catch block
////					e.printStackTrace();
////				}
//			}
//		};
	}
	
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Sample View",
			message);
	}

	public TableViewer getViewer() {
		return viewer;
	}

	public void showSearchResults(java.util.List listOfEntries) {
		if (viewer != null) {
			this.currentCvsSearchEntries = listOfEntries;
			viewer.setInput(this.currentCvsSearchEntries);
		}
		
	}

	public void setChangeLogJob(BackgroundJob job) {
		//this.changeLogJob = changeLogJob;
		
	}
}
